package com.emip.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class BaseDAO {
	@Autowired
	HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> getEntities(Class<?> T, final String hql, final int page, final int pageSize) {
		final int offset =  (page - 1) * pageSize;
		return getHibernateTemplate().executeFind(
			new HibernateCallback<List<T>>(){

				public List<T> doInHibernate(final Session session) 
						throws HibernateException, SQLException {
					Query query = session.createQuery(hql);
					query.setFirstResult(offset);
					query.setMaxResults(pageSize);
					return query.list();
				}
				
			}
		);
	}
	
	public Object getCount(String hql) {
		return getHibernateTemplate().find(hql).listIterator().next();
	}
}
